<template>
  <div class="vacation-rules-container">
    <div class="page-header">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增调拨记录
      </el-button>
    </div>

    <el-table v-loading="loading" :data="dataList" border style="width: 100%">
      <el-table-column label="调出门店" width="150">
        <template #default="scope">
          <span style="color: #e96725">
            {{ scope.row.out_shop.shop_name }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="调入门店" width="150">
        <template #default="scope">
          {{ scope.row.in_shop.shop_name }}
        </template>
      </el-table-column>

      <el-table-column label="调拨类型" min-width="120">
        <template #default="scope">
          <span v-if="scope.row.transfer_name != ''">
            {{ scope.row.transfer_name }}
          </span>
          <span v-else> 不存在的类型 </span>
        </template>
      </el-table-column>

      <el-table-column label="调拨人员" min-width="120">
        <template #default="scope">
          <span v-for="item in scope.row.userid_list"> {{ item.username }}&nbsp </span>
        </template>
      </el-table-column>
      <el-table-column label="调拨时间" min-width="120">
        <template #default="scope">
          {{ scope.row.start_date }} - {{ scope.row.end_date }}
        </template>
      </el-table-column>

      <el-table-column label="调拨状态" width="150">
        <template #default="scope">
          <span
            v-if="scope.row.state == '2'"
            style="
              background-color: #56bc5b;
              display: inline-block;
              border-radius: 5px;
              width: 60px;
              text-align: center;
            "
          >
            通过
          </span>

          <span
            v-else-if="scope.row.state == '1' || scope.row.state == null"
            style="
              background-color: #c0c4cc;
              display: inline-block;
              border-radius: 5px;
              width: 60px;
              text-align: center;
            "
          >
            待审核
          </span>

          <span
            v-else-if="scope.row.state == '3'"
            style="
              background-color: #e96725;
              display: inline-block;
              border-radius: 5px;
              width: 60px;
              text-align: center;
            "
          >
            拒绝
          </span>

          <span
            v-else-if="scope.row.state == '4'"
            style="
              background-color: #e6a23c;
              display: inline-block;
              border-radius: 5px;
              width: 60px;
              text-align: center;
            "
          >
            已撤销
          </span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="操作" width="100" fixed="right">
        <template #default="{ row }">
          <el-button type="danger" link @click="handleDelete(row)"> 删除 </el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <!-- 新增/编辑抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :title="isEdit ? '查看调拨记录' : '新增调拨记录'"
      size="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      direction="rtl"
      class="vacation-drawer"
    >
      <el-form
        ref="postformDataref"
        :model="postformData"
        :rules="rules"
        label-width="120px"
        class="drawer-form"
        :disabled="falccc"
      >
        <el-form-item label="调入门店" prop="in_shop">
          <el-cascader
            v-if="!isEdit"
            style="width: 220px"
            v-model="postformData.in_shop"
            :options="cascaderOptions"
            placeholder="请选择门店"
            clearable
            filterable
          ></el-cascader>

          <el-input
            v-if="isEdit"
            v-model="inshopname"
            style="width: 220px"
            placeholder="当前店铺"
            :disabled="true"
          />
        </el-form-item>

        <el-form-item label="开始日期" prop="start_date">
          <!--日历禁用过期时间 :disabled-date="disabledDate" -->
          <el-date-picker
            v-model="postformData.start_date"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="结束日期" prop="end_date">
          <!--日历禁用过期时间 :disabled-date="disabledDate" -->
          <el-date-picker
            v-model="postformData.end_date"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="调拨类型" prop="transfer_type">
          <el-cascader
            v-if="!isEdit"
            v-model="postformData.transfer_type"
            :options="optionstransfertype"
          />
        </el-form-item>

        <el-form-item label="调出门店" prop="out_shop">
          <el-cascader
            style="width: 220px"
            v-model="postformData.out_shop"
            :options="cascaderOptions_out"
            placeholder="请选择门店"
            clearable
            filterable
            @change="dianbuxzhe"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="调出人员" prop="userid_list">
          <!-- 单选选择器 -->
          <el-select
            v-if="!isEdit"
            style="width: 220px"
            v-model="postformData.userid_list"
            placeholder="请选择用户"
            clearable
            @change="handleChange"
          >
            <el-option
              v-for="item in selectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>

          <el-input
            v-if="isEdit"
            v-model="inshoppouple"
            style="width: 220px"
            placeholder="当前店铺"
            :disabled="true"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="drawer-footer">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" :disabled="falccc" @click="handleSubmit"
            >保存</el-button
          >
        </div>
      </template>
    </el-drawer>

    <div style="display: flex; align-items: center">
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="currentPage4"
          v-model:page-size="pageSize4"
          :page-sizes="[10, 20, 50]"
          :size="size"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalpage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import {
  getSchedulingApprovals,
  deletetransfer,
  getshopuser,
  posttransfer,
  puttransfer,
} from "@/api/allocationManagement";
import { ElMessage } from "element-plus";
import { reactive } from "vue";
import { ElCascader, ElSelect, ElOption } from "element-plus";
import { getStoreInfo, getAllStoreInfo } from "@/api/store";

import { getTagInfo } from "@/api/tag";

import type { ComponentSize } from "element-plus";

const currentPage4 = ref(1);
const pageSize4 = ref(10);
const size = ref<ComponentSize>("default");
const background = ref(false);
const disabled = ref(false);

const totalpage = ref();

const handleSizeChange = async (val: number) => {
  const res = await getSchedulingApprovals(currentPage4.value, pageSize4.value);
  if (res.code == '200') {
    loading.value = false;
    dataList.value = res.data.items;

    ElMessage.success("查询成功");
  } else {
    ElMessage.error("查询失败");
  }
};
const handleCurrentChange = async (val: number) => {
  const res = await getSchedulingApprovals(currentPage4.value, pageSize4.value);
  if (res.code == '200') {
    loading.value = false;
    dataList.value = res.data.items;
    ElMessage.success("查询成功");
  } else {
    ElMessage.error("查询失败");
  }
};

// 初始化列表数据
const dataList = ref(<Array<unknown> | any>[]);
const loading = ref(<boolean>true);

const inshopname = ref("");
const transfertypeaa = ref("");
const inshoppouple = ref("");

// 禁用早于今天的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
};

// 限制修改表格数据，只能查看
const falccc = ref(false);

const drawerVisible = ref(false);
const isEdit = ref(false);

const optionstransfertype = ref([]);

// 表单校验
const postformDataref = ref<any>();

// 表单校验规则
const rules = {
  userid_list: [{ required: true, message: "请选择门店人员", trigger: "change" }],
  in_shop: [{ required: !isEdit.value, message: "请选择调入门店", trigger: "change" }],
  out_shop: [{ required: true, message: "请选择调出门店", trigger: "change" }],
  start_date: [{ required: true, message: "请选择开始时间", trigger: "change" }],
  end_date: [{ required: true, message: "请选择休结束时间", trigger: "change" }],
  transfer_type: [{ required: true, message: "请选择调拨类型", trigger: "change" }],
};

// 表单数据
const postformData = reactive<{
  userid_list?: any;
  in_shop?: any;
  out_shop?: any;
  start_date?: any;
  end_date?: any;
  transfer_type?: any;
  state?: any;
}>({
  userid_list: "",
  in_shop: "",
  out_shop: "",
  start_date: "",
  end_date: "",
  state: "1",
  transfer_type: "",
});

// 新增
const handleAdd = () => {
  falccc.value = false;
  isEdit.value = false;
  Object.assign(postformData, {
    userid_list: "",
    in_shop: "",
    out_shop: "",
    start_date: "",
    end_date: "",
    state: "1",
    transfer_type: "",
  });
  drawerVisible.value = true;
};

// 定义响应式的选项列表和选中的值
const selectOptions = ref([]);
// 转换数据结构以适应 el-select
const transformDataren = (data: any) =>
  data.map(({ userid, username }) => ({
    value: userid,
    label: username,
  }));

// 处理选择变化事件
const handleChange = (value) => {};

// 转换数据结构以适应 el-cascader
const transformData = (data) =>
  data.map(({ selfid, shop_name, childs }) => ({
    value: selfid,
    label: shop_name,
    children: Array.isArray(childs) && childs.length ? transformData(childs) : null,
  }));

// // 定义响应式的选项和选中的值
const cascaderOptions = ref([]);

const cascaderOptions_out = ref([]);

const dianbuxzhe = async (val: any) => {
  if (val != undefined) {
    if (val.length > 1) {
      const res = await getshopuser(val[1]);

      postformData.userid_list = "";
      if (!isEdit.value) {
        if (!res.data.user_list.length > 0) {
          ElMessage.warning("当前门店人员为空不能新建");
        }
      }

      selectOptions.value = transformDataren(res.data.user_list);
    } else {
      const res = await getshopuser(val[0]);
      if (!isEdit.value) {
        if (!res.data.user_list.length > 0) {
          ElMessage.warning("当前区人员为空不能新建");
        }
      }

      selectOptions.value = transformDataren(res.data.user_list);
    }
  }
};

// 转换数据结构以适应 el-select，并且包含子项
const transformDepartmentList = (data) =>
  data.map(({ id, name }) => ({
    value: id,
    label: name,
  }));

onMounted(async () => {
  const resqq = await getStoreInfo();
  cascaderOptions.value = transformData(resqq.result);
  const res = await getAllStoreInfo();
  cascaderOptions_out.value = transformData(res.result);

  const restag = await getTagInfo();
  optionstransfertype.value = transformDepartmentList(restag.data);
});

const handleDelete = async (row: any) => {
  const res = await deletetransfer({
    id: row.id,
  });
  if (res.code == '200') {
    ElMessage.success("删除成功");
    getData();
  } else {
    ElMessage.error(res.msg);
  }
};

// 初始化数据
onMounted(async () => {
  getData();
});

const getData = async () => {
  const res = await getSchedulingApprovals(1, 10);
  loading.value = false;
  dataList.value = res.data.items;

  totalpage.value = res.data.total;
  currentPage4.value = res.data.page;
};

// 定义比较时间的方法
const isTimeGreater = (time1: any, time2: any) => {
  // 将时间字符串转为 Date 对象
  const date1 = new Date(time1);
  const date2 = new Date(time2);

  // 比较两个时间并返回布尔值
  return date1 >= date2;
};

// 提交菜单
const handleSubmit = async () => {
  try {
    await postformDataref.value.validate();

    if (!isTimeGreater(postformData.end_date, postformData.start_date)) {
      ElMessage.warning("结束日期不能小于开始日期！");
      return;
    }

    if (postformData.out_shop.length < 2 || postformData.in_shop < 2) {
      ElMessage.warning("调入调出不能选择区！");
      return;
    }
    if (postformData.out_shop[1] == postformData.in_shop[1]) {
      ElMessage.warning("调入门店不能和调出门店一样");
      return;
    }

      const paramsdata={
        end_date:postformData.end_date,
        start_date:postformData.start_date,
        in_shop:postformData.in_shop[(postformData.in_shop.length-1)],
        out_shop: postformData.out_shop[(postformData.out_shop.length-1)],
        state:'1',
        transfer_type:postformData.transfer_type[(postformData.transfer_type.length-1)],
        userid_list:postformData.userid_list
      }
   
      
      
      const res = await posttransfer(paramsdata);
      if (res.code == '200') {
        ElMessage.success(res.msg);
        drawerVisible.value = false;
        getData();
      } else {
        ElMessage.error(res.msg);
      }

  } catch (error) {
    console.error("表单验证失败:", error);
  }
};
</script>

<style lang="scss" scoped>
.vacation-rules-container {
  height: 83vh;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
  }
}
</style>
